package orz.itrip.trade.controller;


import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import orz.itrip.dto.Dto;
import orz.itrip.trade.config.WXPay.WXPayUtil;
import orz.itrip.trade.service.TradeService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wxpay")
public class WxpayController {

    @Resource
    private TradeService tradeService;
    //微信生成付款二维码：接收到用户付款的请求，服务器就发送付款的请求给微信
    @GetMapping("createqccode/{orderNo}")
    public  Dto createqccode(@PathVariable("orderNo") String orderNo){
        return tradeService.payViaWX(orderNo);
    }
    //微信支付异步回调：付款成功进行异步回调
    @PostMapping("wxnotify")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> mapResult = null;
        try {
            InputStream is = request.getInputStream();
            String xmlResult = IOUtils.toString(is, "utf-8");
            System.out.println(xmlResult);
            mapResult = WXPayUtil.xmlToMap(xmlResult);
            System.out.println("交易成功：" + mapResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //付款成功
        if ("SUCCESS".equals(mapResult.get("return_code")) && "SUCCESS".equals(mapResult.get("result_code"))) {
            //付款成功，得到回调数据，判断是否和发给微信的请求数据是否一致
            //进行数据库的更新操作
            Map<String, String> mapVo = new HashMap<>();
            mapVo.put("return_code", "SUCCESS");
            mapVo.put("result_code", "SUCCESS");
            try {
                //mapResult.get("prepay_id")获取不到，存在问题
                String prePayId = StringUtils.isEmpty(mapResult.get("prepay_id"))?"":mapResult.get("prepay_id");
                tradeService.updateData(mapResult.get("out_trade_no"),prePayId , 2);
                response.getWriter().println(WXPayUtil.mapToXml(mapVo));
                response.getWriter().flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @GetMapping("queryorderstatus/{orderNo}")
    public  Dto queryorderstatus(@PathVariable("orderNo") String orderNo){
        return tradeService.queryorderstatus(orderNo);
    }
}
